﻿using System;
using System.Windows;
using DSPL.Services;
using DSPL.Contracts;
using DSPL.Common;
using System.Data;
using DSPL.Services.Services;
using DSPL.Contracts.Common;
using DSPL.Contracts.ViewModel;
using DSPL.Contracts.Command;
using DSPL.Finac.Common;
using System.Windows.Input;

namespace DSPL.Finac.ViewModel
{
    public class TaxCombinationMasterViewModel : BaseViewModel
    {
        private bool isTaxCombCodeFocused;
        private bool isTaxCombNameFocused;       
        private DataTable _dtTaxDet;       
        private DataRow _dtTaxRow;
        private ICommand cellEditEnding;
        private ICommand refreshAttachedObjects;
        private int rowCount = 0;

        #region Define properties

        public bool IsTaxCombCodeFocused
        {
            get { return isTaxCombCodeFocused; }
            set
            {
                isTaxCombCodeFocused = value;
                this.OnPropertyChanged("IsTaxCombCodeFocused");

            }
        }

        public bool IsTaxCombNameFocused
        {
            get { return isTaxCombNameFocused; }
            set
            {
                isTaxCombNameFocused = value;
                this.OnPropertyChanged("IsTaxCombNameFocused");

            }
        }

        public DataRow TaxSelectedRow
        {
            get
            {
                return _dtTaxRow;
            }
            set
            {
                _dtTaxRow = value;
                this.OnPropertyChanged("TaxSelectedRow");
            }
        }

        public DataTable DtTaxDet
        {
            get
            {
                return _dtTaxDet;
            }
            set
            {
                _dtTaxDet = value;
                this.OnPropertyChanged("DtTaxDet");
            }
        }
        
        public ICommand CellEditEnding
        {
            get
            {
                if (this.cellEditEnding == null)
                    this.cellEditEnding = new RelayCommand(CellEditEndingExecuted);

                return this.cellEditEnding;
            }
        }
        
        public ICommand RefreshAttachedObjects
        {
            get
            {
                if (this.refreshAttachedObjects == null)
                    this.refreshAttachedObjects = new RelayCommand(RefreshAttachedObjectsExecuted);

                return this.refreshAttachedObjects;
            }
        }
        
               
        #endregion


        #region Constructor

        public TaxCombinationMasterViewModel()
            : base()
        {
            MessageTitle = "Tax Combination Master";
        }

        #endregion
       
        /// <summary>
        /// Validate mandatory data before save
        /// </summary>
        /// <param name="obj"></param>
        protected override void PreDataValidateExecuted(object obj)
        {
            IsTaxCombCodeFocused = false;            
            IsTaxCombNameFocused = false;

            var messageService = new MessageService();
            if (string.IsNullOrEmpty(CurrentRow["TaxComCode"].ToString().Trim()))
            {
                messageService.ShowMessage(MessageText.TaxCombCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsTaxCombCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (string.IsNullOrEmpty(CurrentRow["TaxComName"].ToString().Trim()))
            {
                messageService.ShowMessage(MessageText.TaxCombNameNotEmpty, MessageTitle, MessageType.InfoOK);
                IsTaxCombNameFocused = true;
                this.IsValid = false;
                return;
            }

            if (DtTaxDet.Select("TaxCode<>'' AND TaxRate>0 AND TaxSeq>0").Length == 0)
            {
                 messageService.ShowMessage(MessageText.InvalidTaxData, MessageTitle, MessageType.InfoOK);

                if (DtTaxDet.Rows.Count == 0)
                {
                    DataRow drTax = DtTaxDet.NewRow();
                    drTax["TaxCode"] = "";
                    drTax["TaxName"] = "";
                    drTax["TaxPer"] = 0.00;
                    drTax["TaxRate"] = 0.00;
                    drTax["TaxPer"] = 0.00;
                    drTax["TaxComPk"] = (CurrentRow["TaxComPk"] == DBNull.Value ? 0 : Convert.ToInt32(CurrentRow["TaxComPk"]));
                    DtTaxDet.Rows.Add(drTax);
                }
                this.IsValid = false;
                return;
            }


            this.IsValid = true;
        }

        protected override void RefreshExternalDataObjectsExecueted(object obj)
        {

            base.RefreshExternalDataObjectsExecueted(obj);

            if (FormMode == Modes.New)
            {
                CurrentRow["Active"] = 1;
                
                OnPropertyChanged("CurrentRow");
            }

            SetTaxDetails();
        }


        private void SetTaxDetails()
        {
            var commonService = new MasterReadService();
            int taxComPk;
            if (FormMode == Modes.New)
            {
                taxComPk  =0;
            }
            else
            {
                taxComPk =Convert.ToInt32(CurrentRow["TaxComPk"]);
            }
            
            DtTaxDet = commonService.GetTaxCombinationDetails(taxComPk);
           
        }

        /// <summary>
        /// To delete related records from child tables before deletes the master data.
        /// </summary>
        /// <returns></returns>
        protected override void PreDataDeleteExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.DeleteTaxCombinationSpecificData(Convert.ToInt32(CurrentRow["TaxComPk"]), ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }

        /// <summary>
        /// To build up the insert statements to update related child tables.
        /// </summary>
        /// <param name="writeData"></param>
        /// <returns></returns>
        /// 
        protected override void PostDataUpdateExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.UpdateTaxCombinationData(CurrentRow, DtTaxDet, ref sqlTran))
            {
                this.IsValid = false;
            }
          
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }


        /// <summary>
        /// To build up the insert statements to update related child tables.
        /// </summary>
        /// <param name="writeData"></param>
        /// <returns></returns>
        /// 
        protected override void PostDataInsertExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.UpdateTaxCombinationData(CurrentRow, DtTaxDet, ref sqlTran))
            {
                this.IsValid = false;
            }
           
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }
        }

        /// <summary>
        /// To refresh the datagrid, when cell value chnaging
        /// </summary>
        private void CellEditEndingExecuted(object obj)
        {
            OnPropertyChanged("DtChildTransaction");
            rowCount = DtChildTransaction == null ? 0 : DtChildTransaction.Rows.Count;
        }

        /// <summary>
        /// To refresh the external data objects of txtMaster
        /// </summary>
        private void RefreshAttachedObjectsExecuted(object obj)
        {
            DtChildTransaction.Rows[rowCount]["TaxName"] = TaxSelectedRow["TaxName"];
            DtChildTransaction.Rows[rowCount]["TaxPer"] = TaxSelectedRow["TaxPer"];
            DtChildTransaction.Rows[rowCount]["TaxRate"] = TaxSelectedRow["TaxRate"];

        }

        private void RefreshData()
        {
            if (TaxSelectedRow != null)
            {
                DtChildTransaction.Rows.Add(DtChildTransaction.NewRow());
                DtChildTransaction.Rows[rowCount]["TaxName"] = TaxSelectedRow["TaxName"];
                DtChildTransaction.Rows[rowCount]["TaxPer"] = TaxSelectedRow["TaxPer"];
                DtChildTransaction.Rows[rowCount]["TaxRate"] = TaxSelectedRow["TaxRate"];
            }
        }


    }
}